<template>
  <div class="book-management">
    <div class="header">
      <h1>图书管理</h1>
      <button class="btn btn-primary" @click="openBookForm(null)">添加图书</button>
    </div>

    <div class="card">
      <div class="search-bar">
        <input type="text" v-model="bookSearch" placeholder="搜索图书..." style="flex:1">
        <select v-model="bookFilter">
          <option value="all">全部状态</option>
          <option value="在库">在库</option>
          <option value="借出">借出</option>
          <option value="维护中">维护中</option>
        </select>
        <button class="btn btn-primary" @click="searchBooks">搜索</button>
      </div>

      <div class="table-container">
        <table>
          <thead>
          <tr>
            <th>ISBN</th>
            <th>书名</th>
            <th>作者</th>
            <th>出版社</th>
            <th>出版日期</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="book in filteredBooks" :key="book.id">
            <td>{{ book.isbn }}</td>
            <td>{{ book.title }}</td>
            <td>{{ book.author }}</td>
            <td>{{ book.publisher }}</td>
            <td>{{ formatDate(book.publishDate) }}</td>
            <td>
                <span :class="'status-' + (book.status === '在库' ? 'available' : 'borrowed')">
                  {{ book.status }}
                </span>
            </td>
            <td class="action-buttons">
              <button class="btn btn-success" @click="openBookForm(book)">编辑</button>
              <button class="btn btn-danger" @click="deleteBook(book.id)">删除</button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 图书表单弹窗 -->
    <div v-if="showBookForm" class="modal">
      <div class="modal-content">
        <span class="close" @click="showBookForm = false">&times;</span>
        <h2>{{ currentBook.id ? '编辑图书' : '添加图书' }}</h2>

        <div class="form-group">
          <label>ISBN</label>
          <input type="text" v-model="currentBook.isbn">
        </div>

        <div class="form-group">
          <label>书名</label>
          <input type="text" v-model="currentBook.title">
        </div>

        <div class="form-group">
          <label>作者</label>
          <input type="text" v-model="currentBook.author">
        </div>

        <div class="form-group">
          <label>出版社</label>
          <input type="text" v-model="currentBook.publisher">
        </div>

        <div class="form-group">
          <label>出版日期</label>
          <input type="date" v-model="currentBook.publishDate">
        </div>

        <div class="form-group">
          <label>分类</label>
          <input type="text" v-model="currentBook.category">
        </div>

        <div class="form-group">
          <label>状态</label>
          <select v-model="currentBook.status">
            <option value="在库">在库</option>
            <option value="借出">借出</option>
            <option value="维护中">维护中</option>
          </select>
        </div>

        <button class="btn btn-primary" @click="saveBook">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import BookService from '@/services/book';

export default {
  setup() {
    const books = ref([]);
    const bookSearch = ref('');
    const bookFilter = ref('all');
    const showBookForm = ref(false);
    const currentBook = ref({
      id: null,
      isbn: '',
      title: '',
      author: '',
      publisher: '',
      publishDate: '',
      category: '',
      status: '在库'
    });

    const loadBooks = async () => {
      try {
        books.value = await BookService.getAllBooks();
      } catch (error) {
        console.error('获取图书列表失败:', error);
      }
    };

    onMounted(loadBooks);

    const filteredBooks = computed(() => {
      let result = books.value;

      // 按状态过滤
      if (bookFilter.value !== 'all') {
        result = result.filter(book => book.status === bookFilter.value);
      }

      // 按搜索词过滤
      if (bookSearch.value) {
        const searchTerm = bookSearch.value.toLowerCase();
        result = result.filter(book =>
            book.title.toLowerCase().includes(searchTerm) ||
            book.author.toLowerCase().includes(searchTerm) ||
            book.isbn.toLowerCase().includes(searchTerm)
        );
      }

      return result;
    });

    const openBookForm = (book) => {
      if (book) {
        currentBook.value = { ...book };
      } else {
        currentBook.value = {
          id: null,
          isbn: '',
          title: '',
          author: '',
          publisher: '',
          publishDate: '',
          category: '',
          status: '在库'
        };
      }
      showBookForm.value = true;
    };

    const saveBook = async () => {
      try {
        if (currentBook.value.id) {
          await BookService.updateBook(currentBook.value);
        } else {
          await BookService.addBook(currentBook.value);
        }
        showBookForm.value = false;
        loadBooks();
      } catch (error) {
        console.error('保存图书失败:', error);
      }
    };

    const deleteBook = async (id) => {
      if (confirm('确定要删除这本图书吗？')) {
        try {
          await BookService.deleteBook(id);
          loadBooks();
        } catch (error) {
          console.error('删除图书失败:', error);
        }
      }
    };

    const searchBooks = () => {
      // 搜索逻辑已在计算属性中实现
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    };

    return {
      books,
      bookSearch,
      bookFilter,
      filteredBooks,
      showBookForm,
      currentBook,
      openBookForm,
      saveBook,
      deleteBook,
      searchBooks,
      formatDate
    };
  }
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  position: relative;
}

.close {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
}
</style>